<template>
    <div id="app" class="detail" :class="{'night':moreConfig.night,'page-loading':pageLoading,'in-app':isApp}">
        <scroll-fixed v-if="!isApp">
            <page-bar @right="moreConfig.status = true">
                <div slot="middle" class="header-middle">{{info.source}}</div>
            </page-bar>
            <a href="javascript:;" @click="appDownload" class="app-download" :class="{'hide':hideDownload}">
                <div class="app-logo">
                    <img src="../assets/app_logo.png"> 泛亚资讯
                </div>
                <span>打开</span>
            </a><!-- end app-download -->
        </scroll-fixed>
        <ui-loading v-if="pageLoading">
            <div slot="content"></div>
        </ui-loading>
        <page-error v-else-if="pageError" @refresh="pageRefresh"></page-error>
        <scroll-list ref="scroll" v-else class="ui-list" :disabled="true" :config="scroll" @bottom="loadmore">      
            <div class="detail-cont">
                <div class="header wrap"  v-if="!isApp">
                    <p class="tit" id="title">{{info.subtitle}}</p>
                    <p class="info">
                        <span>{{info.source}}</span>
                        <span>{{info.issue_date}}</span>
                    </p>
                </div>
                <div id="cont" class="cont" @click="previewImageAction($event)" :class="{'xs':moreConfig.range == 1,'sm':moreConfig.range == 2,'normal':moreConfig.range==3,'md':moreConfig.range == 4,'lg':moreConfig.range == 5}" v-html="info.content"></div>
                <div class="source-box" v-if="info.is_show_source">
                    <p>原网页由 泛亚资讯 转码以便移动设备阅读</p>
                    <a :href="info.source_url">查看原文</a>
                </div>
            </div><!-- detaiil-cont -->
            
            <a class="hot-rec" href="/hot.html" v-if="hot_list && hot_list.length > 0">
                <div class="hot-rec-tit">
                    <p>热点</p><p>精选</p>
                </div>
                <a :href="hot_list[0].detail_url" class="hot-rec-cont">
                    hot_list[0].title
                </a>
            </a><!-- end hot-rec -->

            <template v-if="!isApp">
                <div class="push-list" v-if="recom_list.length > 0">
                    <div class="header">
                        <span>延展阅读</span>
                        <i></i>
                    </div>
                    <div class="list">
                        <ui-item v-for="item in recom_list" :item="item" :key="item.id"></ui-item>
                    </div>
                </div><!-- end pull-list -->

                <div class="comment-list">
                    <div class="header">
                        <span>各方观点</span>
                        <i></i>
                    </div>
                    <div class="list">
                        <p class="tit">全部评论({{info.comment_count}})</p>
                        <ui-comment-item v-for="item in comment.list" :item="item" :showInfo="false" :type='5' :key="item.id" @del="delItem"></ui-comment-item>
                    </div>
                </div><!-- comment-list -->
            </template>
        </scroll-list> 
        <offline v-if="!isApp" />
    
        <popup-more :status="moreConfig.status" :config="moreConfig" @font="fontChange" @report="report_status = true,moreConfig.status=false" @unlike="unlikeHandle" @close="moreConfig.status = false" @fav="changeFav" @night="changeNight"></popup-more>
        <transition name="page-slide-left">
            <ui-report v-if="report_status" :id="info.id" :type="info.type" :title="info.title" @cancel="reportCancel" @done="reportDone"/>
        </transition>

        <ui-preview :config="preview" v-if="preview.status" @close="preview.status = false"/>
        <ui-comment  v-if="!isApp" ref="comment" @done="commentDone"/>

         <slide-tool ref="slide" v-if="!isApp" :type="'comment'"/>
    </div>
</template>
<script>
import Items from '../components/items.vue'
import pageBar from '../components/pagebar.vue'
import scrollFixed from '../components/scrollFixed.vue'
import UILoading from '../components/loading.vue'
import pageError from '../components/pageError.vue'
import offline from '../components/offline.vue'
import UIComment from '../components/comment.vue'

import uiPreview from '../components/preview.vue'

import MoreBox from '../components/morebox.vue'

import mxReport from '../mixins/report.js'
import reportVue from '../components/report.vue';
import ScrollList from "../components/scrollList.vue";
import commentItem from "../components/commentItem.vue";

import mxSlide from "../mixins/slide.js";


import Lazy from '../plugins/lazy.js'

export default {
    name:'detail',
    data(){
        return {
            id:'',
            info:{},
            hideDownload:false,
            isApp:this.$utils.app.isApp,
            moreConfig:{
                id:'',
                status:false,
                fav:false,
                night:false,
                font:true,
                range:3,
            },
            preview:{
                status:false,
                delete:false,
                active:0,
                list:[]
            },
            pageLoading:true,
            pageError:false,
            recom_list:[],
            hot_list:[],
            scroll:{
                bottom:false
            },
            comment:{
                is_end:this.$utils.app.isApp,//app的情况下不需要加载跟多,
                page_no:1,
                list:[]
            }
        }
    },
    mixins:[mxReport,mxSlide],
    mounted(){
        let lazy;
        this.$on('pageRefresh',()=>{
            this.pageLoading = true;
            this.loadPage().then(rs=>{
                this.pageLoading = false;
                this.$nextTick().then(()=>{
                    //一次性加载所有图片
                    if(this.isApp){
                        let imgs = document.querySelectorAll('img[data-src]');
                        let len = imgs.length;
                        if(len ==0) return false;
                        for(let i = 0;i<len;i++){
                            let img = imgs[i];
                            let src = img.getAttribute('data-src');
                            img.setAttribute('src',src);
                        }
                    }else {
                        lazy = new Lazy();
                        this.$refs.comment.$emit('init',{type:'add',count:this.info.comment_count,info:this.info});
                    }
                });


            }).catch(e=>{
                this.pageError = true;
            }).finally(()=>{
                this.pageLoading = false;
            });

            !this.isApp && this.getCommentList().then(() => {
                this.$nextTick(() => {
                    this.scroll.bottom = this.comment.is_end ? 'done' : false;
                });
            });
        })
        //获取默认字体大小
        let font = this.$utils.caches.get('font');
        this.moreConfig.range = isNaN(parseInt(font)) ? 3: parseInt(font);

        let parse = this.$utils.urlFactory.parse(location.search);
        if(parse && parse.id){
            this.id = parse.id;
            this.$emit('pageRefresh');
        }else{
            this.$toast('参数有误').then(()=>{
                history.back();
            })
        }

        !this.isApp && this.$on('SCROLL',(e,params)=>{
            this.hideDownload = params.top >= params.height * 0.9;     
        })

    },
    components:{
        [Items.name]:Items,
        [pageBar.name]:pageBar,
        [scrollFixed.name]:scrollFixed,
        [pageError.name]:pageError,
        [offline.name]:offline,
        [UILoading.name]:UILoading,
        [MoreBox.name]:MoreBox,
        [UIComment.name]:UIComment,
        [uiPreview.name]:uiPreview,
        [ScrollList.name]:ScrollList,
        [commentItem.name]:commentItem,
    },
    destroyed(){
        window.copy_url = ''
    },
    methods:{
        unlikeHandle(){
            history.back();
        },
        loadPage(){
            let urlParams = this.$utils.urlFactory.parse(location.search);
            let params = {
                id:this.id
            }
            if(urlParams.action && urlParams.action == 'preview'){
                params.action = 'preview'
            }

            return this.$http.get('?ct=news&ac=detail',{params}).then(response=>{
                let {data} = response;
                if(data.code == 0){
                    let rs = data.data;
                    let self = this;
                    rs.info.content = rs.info.content.replace(/<img([\s\S]*?)src\s*=\s*(['"])([\s\S]*?)\2([^>]*)>/gi,`<img$1data-src=$2$3$2$4 src="" lazy>`)
                    rs.info.content = rs.info.content.replace(/<img([\s\S]*?)width\s*=\s*(['"])([\s\S]*?)\2([\s\S]*?)height\s*=\s*\2([\s\S]*?)\2([^>]*)>/gi,function(){
                        let size = self.getImageSize(arguments[3],arguments[5]);
                        return `<img${arguments[1]} width=${arguments[2]}${size.width}px${arguments[2]}${arguments[4]}height=${arguments[2]}${size.height}px${arguments[2]}${arguments[6]} >`
                    })
                    // rs.info.content = rs.info.content.replace(/<video([\s\S]*?)src\s*=\s*(['"])([\s\S]*?)\2([^>]*)>/gi,'<div data-plugin="video"$1src=$2$3$2$4></div>')
                    // rs.info.content = rs.info.content.replace(/<video/gi,'<div data-plugin="video"');
                    // rs.info.content = rs.info.content.replace(/<\/video>/gi,'</div>');
                    this.info = rs.info;
                    rs.info.detail_url = location.href;

                    //设置复制链接，如果morebox里用到
                    window.copy_url = rs.info.copy_url;

                    //添加历史记录
                    this.$utils.history.set(rs.info);


                    this.info.format_time = this.$moment(this.info.issue_time * 1000).format("MM/DD hh:mm");
                    
                    //是否已经收藏
                    this.moreConfig.fav = !!this.info.is_collect;
                    this.moreConfig.id = this.info.id;

                    let list = [];
                    rs.recom_list.forEach(item=>{
                        if(this.$utils.unlike.check(item.id)) return;
                        let tmpItem = item;
                      
                        tmpItem.url = item.detail_url;
                        tmpItem.src = item.cover_img[0];
                        tmpItem.source = item.source;
                        tmpItem.view = item.browse_total;
                        tmpItem.time = this.$moment(item.issue_time * 1000).fromNow().replace(' ','');
                        
                        //防止显示置顶和热点的字样，收到改成1
                        tmpItem.is_hot = 0;
                        tmpItem.is_top = 0;
                        //设计稿这里只有normal类型的新闻
                        tmpItem.type = 'normal';
                        
                        list.push(tmpItem);
                    });

                    this.recom_list = list;
                }else{
                    let co = this.$toast(data.msg);
                    if(data.code == 5003 || data.code == 5004){
                        co.then(()=>{
                            history.back();
                        })
                    }
                    throw new Error(data.msg);
                }
            }).catch(e=>{
                this.$toast(e);
                throw e;
            })
        },
        fontChange(range){
            this.moreConfig.range = range;
            this.$utils.caches.set('font',range);
        },
        changeFav(flag){
            this.moreConfig.fav = flag;
            this.moreConfig.status = false;
        },
        changeNight(flag){
            this.moreConfig.night = !this.moreConfig.night;
            this.moreConfig.status = false;
        },
        pageRefresh(){
            this.pageError = false;
            this.$emit('pageRefresh');
        },
        previewImage(idx){
            this.preview.active = idx;
            this.preview.status = true;
        },
        previewImageAction(e){
            if(e.target.tagName.toUpperCase() === 'IMG'){
                if(this.preview.list.length == 0){
                    let imgs = e.currentTarget.querySelectorAll('img');
                    for(let i = 0,len = imgs.length;i<len;i++){
                        imgs[i].dataset.idx = i;
                        let src = imgs[i].getAttribute('data-src')
                        this.preview.list.push(src);
                    }
                }
                if(this.preview.list.length>0){
                    let idx = e.target.dataset.idx;
                    if(this.isApp){
                        location.href = this.$utils.app.link.preview + '/' + idx;
                        window.getImages = ()=>this.preview.list;

                    }else{
                        this.previewImage(idx);
                    }

                }
               
            }
        },
        getCommentList(){
            return this.$http.get('?ct=comment&ac=get_list&foreign_id='+this.id+'&page_no='+this.comment.page_no).then(response=>{
                let {data} = response;
                if(data.code == 0){
                    this.comment.is_end = !data.data.is_have_data;
                    this.comment.list = this.comment.list.concat(data.data.list);
                    this.comment.page_no++;
                }else{
                    this.$toast(data.msg);
                }
            }).catch(e=>{
                this.$toast('获取评论数据失败');
            })
        },
        commentDone(rs){
            this.comment.list.unshift(rs)
            this.info.comment_count = this.comment.list.length;
        },
        reply(item){
            this.$refs.comment.$emit('edit',{
                type:'reply',
                count:item.reply_total,
                info:item
            })
        },
        loadmore(){
            if (this.scroll.bottom || this.comment.is_end) return false;
            this.scroll.bottom = true;
            this.getCommentList().then(() => {
                this.$nextTick(() => {
                    this.scroll.bottom = this.comment.is_end ? 'done' : false;
                });
            });
        },
        appDownload(){
            location.href = this.$utils.app.link.open_detail + '' + this.id;

            setTimeout(()=>{
                if (this.$utils.app.ios) {
                    location.href = this.$utils.app.download.ios
                } else {
                    location.href = this.$utils.app.download.android
                }
            },2000);
        },
        delItem(id) {
            let item = this.comment.list.filter((res)=> {
                return res.id == id
            })
            let index = this.comment.list.indexOf(item[0]);
            if(index != -1) {
                this.comment.list.splice(index, 1);
                this.info.comment_count = this.comment.list.length;
            }
        },
        getImageSize(width,height){
            //#cont 的padding宽度
            let padding = lib.flexible.rem2px(30/75);
            //#cont 可显示内容的宽度
            let display_width = window.innerWidth - 2 * padding;
            let ratio = width / height;

            let img_width,img_height;
            if(width>display_width){
                img_width = display_width;
            }else{
                img_width = width;
            }

            img_height = img_width / ratio;
            return {
                width:img_width,
                height:img_height
            }
        },
    }    
}
</script>
<style lang="less">
.detail {
    background-color:#fff;
    color:#161a24;
    
    &.night {
        .page-bar {
            border-bottom: 0.013333rem solid #58443f;
        }
        &,.page-bar,.list-item {
            background-color:#282423;
        }
        color:#fff;

        .list-item{
             .tit {
                 color:#fff;
             }
        }
    }

    .sticky {
       .header-middle {
           opacity:1;
       } 
    }
    .header-middle {
        transition: opacity .2s;
        font-size:34px;
        color:#141414;
        opacity: 0;
    }

    .detail-cont {
        .header.wrap {
            margin-bottom:40px;
            padding:0 30px;
        }
        .tit {
            font-size:44px;
            line-height: 64px;
            font-weight: bold;
        }
        .info {
            margin-top:20px;
            font-size:24px;
            color:#919191;
            span:first-child {
                color:#a98273;
            }
            span + span {
                margin-left:12px;
            }
        }
        
        .cont {
            position:relative;
            padding:0 30px;
            line-height: 62/36;
            word-break: break-word;
            overflow: hidden;
            table{
                width:100%;
            }
            &.normal {
                font-size:36px!important;
            }
            &.xs {
                font-size:28px!important;
            }
            &.sm {
                font-size:32px!important;
            }
            &.md {
                font-size:40px!important;
            }
            &.lg {
                font-size:44px!important;
            }
            img {
                display: block;
                margin:0 auto 20px;
                max-width:100% !important;
                // height:auto;
            }
            
            p,div,span,pre {
                margin-bottom:20px;
                // word-wrap: break-word;
                text-align: justify;
                word-break: break-word;
                word-break: break-all;
                text-indent: 0!important;
            }
            a {
                color:#337ab7;
            }
            video,iframe,embed {
                display: block;
                max-width:100%;
                // height:auto;
                margin: auto;
            }
            video,embed {
                background-color:rgb(45,45,45)
            }
        }
    }
    .push-list,
    .comment-list {
        padding-top:58px;
        .header {
            margin-bottom:40px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size:38px;
            font-weight: bold;
            line-height: 1;

            i {
                margin-top:20px;
                display: block;
                width:32px;
                height:12px;
                background-color:#a98273;
                border-radius:6px;
            }
        }
    }
    .ui-list {
        //底部栏的高度
        padding-bottom:104px;
    }

    &.in-app {
        .ui-list {
            padding-bottom:0
        }
    }

    .comment-list {
        
        .list {
            padding:0 30px;

            &>.tit {
                font-size:28px;
                color:#282828;
                font-weight: bold;
                margin-bottom:8px;
            }
        }
    }

    .font-setting {
        position: absolute;
        left:0;
        right:0;
        bottom:0;
        z-index:2;
        background-color:#fff;
        overflow: hidden;
        .option {
            padding-top:50px;
            margin-bottom:50px;
            display: flex;
            .item {
                flex:1;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                font-size:28px;
                color:#282828;
                span {
                    margin-top:12px;
                    line-height: 1;
                }
            }
        }
        .slide {
            padding-top:32px;
            border-bottom:1px solid #efefef;
            .pick {
                position:relative;
                height:30px;
                span {
                    position: absolute;
                    top:0;
                    line-height: 30px;
                    color:#919191;
                    font-size:28px;
                    text-align: center;
                    &:first-child {
                        left:0%;
                    }
                    &:nth-of-type(2){
                        left:25%;
                        transform: translateX(-50%)
                    }
                    &:nth-of-type(3){
                        left:50%;
                        transform: translateX(-50%)
                        
                    }
                    &:nth-of-type(4){
                        left:75%;
                        transform: translateX(-50%)
                        
                    }
                    &:nth-of-type(5){
                        right:0;
                    }

                    &.on {
                        color:#e64a19;
                    }
                    
                }
            }
            .range {
                position: relative;
                height:130px;
                display: flex;
                justify-content: center;
                align-items: center;
                .line {
                    position:relative;
                    height: 4px;
                    width:100%;
                    border-radius:10px;
                    background-color:#efefef;

                    span {
                        position: absolute;
                        height:100%;
                        background: #e64a19;

                        &::after {
                            content:'';
                            position: absolute;
                            right:0;
                            width:30px;
                            height:30px;
                            border-radius:50%;
                            background-color:#e64a19;
                            transform: translate(50%,-50%);
                        }
                    }
                }
                input[type=range] {
                    position:absolute;
                    top:0;
                    left:0;
                    width:100%;
                    height:100%;
                    opacity:0;
                    -webkit-appearance: none; /* Hides the slider so that custom slider can be made */
                    width: 100%; /* Specific width is required for Firefox. */
                    // background: transparent; /* Otherwise white in Chrome */
                }


                input[type=range]:focus {
                    outline: none; /* Removes the blue border. You should probably do some kind of focus styling for accessibility reasons though. */
                }

                input[type=range]::-webkit-slider-thumb {
                    -webkit-appearance: none;
                    border: none;
                    height: 30px;
                    width: 30px;
                    border-radius: 50%;
                    background: #e64a19;
                    cursor: pointer;
                    margin-top: -13px; /* You need to specify a margin in Chrome, but in Firefox and IE it is automatic */
                }

                input[type=range]::-webkit-slider-runnable-track {
                    height: 4px;
                    background-color:#efefef;
                    border-radius: 10px; /*将轨道设为圆角的*/
                }
                input[type=range]:focus::-webkit-slider-runnable-track {
                    background: #e64a19;
                }
            }
        }
        .slide,.cancel {
            margin:0 30px;
            
        }
        .cancel {
            display: flex;
            justify-content: center;
            align-items: center;
            border-top:1px solid #efefef;
            height:100px;
            color:#919191;
            font-size:32px;
        }
    }

    .detail-end {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 106px;
        color:#c6c6c6;
        font-size:28px;
    }

    .hot-rec {
        margin:0 30px 60px;
        border:1px solid #efefef;
        border-left:3px solid #e64a19;
        height:140px;
    }

    .hot-rec,.hot-rec-tit {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .hot-rec-tit {
        flex-shrink: 0;
        flex-grow: 0;
        flex-direction: column;
        font-weight: bold;
        font-size:36px;
        line-height: 42px;
        color:#282828;
        width:138px;
        height:79px;
        border-right: 2px solid #efefef;
    }
    .hot-rec-cont {
        flex:1;
        padding:0 30px;
        font-size:32px;
        color:#282828;
        line-height: 48px;
    }
    .source-box {
        padding:60px 30px;
        text-align: center;
        font-size:28px;

        p {
            color:#999;
            margin-bottom:20px;
        }
        a {
            color:#e64a19;
        }
    }
}
</style>

